package com.javabaas.server.novel_server.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javabaas.server.novel_server.common.StatusCode;
import com.javabaas.server.novel_server.exception.ServiceException;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class HeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String contentType = httpServletRequest.getHeader("Content-Type");
        if (httpServletRequest.getMethod().equals("OPTIONS")) {
            //遇到OPTIONS请求时直接返回成功
            httpServletResponse.setStatus(200);
            return false;
        }
        if (StringUtils.isEmpty(contentType) || !contentType.contains("application/json")) {
            //检查contentType
            httpServletResponse.setStatus(400);
            Map map = new HashMap();
            map.put("code", 400);
            map.put("msg", "ContentType must be application/json");
            ObjectMapper mapper = new ObjectMapper();
            httpServletResponse.getWriter().write(mapper.writeValueAsString(map));
            return false;
        }

        if (!checkPlatform(httpServletRequest.getHeader("plat"))) {
            //检查platform
            throw new ServiceException(StatusCode.STATUS_PLATFORM_ERROR);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean checkPlatform(String platform) {
        if (StringUtils.isEmpty(platform)) return false;
        if (platform.equals("ios") || platform.equals("android")) return true;
        return false;
    }

}
